package org.hit.burkun.umls;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;

public class GeneralQuery extends BaseQuery {
	/**
	 * 获取对应的umls id
	 * 
	 * @param umlsdbh
	 *            获取umls记录的数据库连接类
	 * @param tbName
	 */
	public GeneralQuery(DBHelper umlsdbh, String tbName, boolean insertUnMapped) {
		super(umlsdbh, tbName);
		this.insertUnMapped = insertUnMapped;
	}

	private boolean insertUnMapped = false;

	public GeneralQuery(DBHelper umlsdbh, String tbName) {
		this(umlsdbh, tbName, false);
	}

	@Override
	public void process(Map<String, Set<String>> data) {
		mapResult.putAll(data);
	}

	public void quickMap(Collection<String> ids, Entity.TYPE type) {
		this.type = type;
		mappedIDs.addAll(ids);
		map(ids, "umls_cui", "db_id", "db_type='" + type + "'");
	}

	public Map<String, Set<String>> getResult() {
		if (insertUnMapped) {
			// 如果当前设定没有map上的需要生成一个唯一的id
			mappedIDs.removeAll(mapResult.keySet());
			Map<String, Set<String>> umapRes = getUnmapped(mappedIDs, type);
			if (umapRes != null) {
				mapResult.putAll(getUnmapped(mappedIDs, type));
			}
		}
		return mapResult;
	}

	@Override
	protected void finalize() throws Throwable {
		if (insertUnMapped) {
			super.finalize();
		}
	}

	private Map<String, Set<String>> mapResult = new HashMap<String, Set<String>>();
	private HashSet<String> mappedIDs = new HashSet<String>();
	private Entity.TYPE type;

	/**
	 * 返回dbid - umls set
	 * 
	 * @param type
	 * @return
	 */
	public static HashMap<String, HashSet<String>> getEntityUmlsMap(
			Entity.TYPE type) {
		DBHelper dbh = DBHelper.getServerData();
		dbh.connectionDB();
		Collection<String[]> res = dbh.queryData(
				"SELECT umls_cui, db_id FROM biodata.map_umls_ids where db_type = '"
						+ type.getTag() + "'", 2);
		dbh.disconnection();
		HashMap<String, HashSet<String>> doumls = new HashMap<String, HashSet<String>>();
		for (String[] line : res) {
			if (doumls.containsKey(line[1])) {
				doumls.get(line[1]).add(line[0]);
			} else {
				HashSet<String> u = new HashSet<String>();
				u.add(line[0]);
				doumls.put(line[1], u);
			}
		}
		return doumls;
	}
}
